<template>
  <div class="page">
    <div class="back" :style="{ top: safeArea_top + 'px' }" @click="back">
      <img src="@/assets/icon/fanhui_1.png" class="img" />
    </div>
    <div id="map"></div>
    <div class="container">
      <div class="bg">
        <div class="search">
          <img src="@/assets/icon/search.png" class="img" />
          <input
            v-model="keyword"
            placeholder="搜索地点"
            class="input"
            @keydown.enter="searchHandle"
          />
          <div class="btn" @click="searchHandle">搜索</div>
        </div>
        <div class="address" v-if="!loading">
          <div
            class="item"
            v-for="item in address.pois"
            :key="item.id"
            @click="itemClick(item)"
          >
            <img src="@/assets/icon/dingwei.png" class="item-img" />
            <div class="info">
              <div class="title">{{ item.title }}</div>
              <div class="address-info">
                <span class="distance">{{
                  getdistence(
                    address.location.lat,
                    address.location.lng,
                    item.location.lat,
                    item.location.lng
                  )
                }}</span>
                <span>{{ item.address }}</span>
              </div>
            </div>
            <div class="check">
              <img
                v-if="checked === item.id"
                src="@/assets/icon/icon_right.png"
                class="item-img"
              />
            </div>
          </div>
        </div>
        <div v-else class="loading address">
          <div class="loading-box">
            <img src="@/assets/icon/icon_loading.png" class="img" />
          </div>
        </div>
        <div class="confirm" @click="confirmSelection">确认选点</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import axios from "axios";
import { getdistence, debounce } from "@/utils/index";
import { ref, onMounted } from "vue";
import { useRoute } from "vue-router";

const route = useRoute();

const checked = ref(null);
const obj = {
  lat: route.query.lat ?? 29.851431477865,
  lng: route.query.lng ?? 107.06816786024,
};
const address = ref([]);
const keyword = ref("");
const loading = ref(false);
const isUpdateList = ref(true);
const safeArea_top = ref(route.query.top);

const itemClick = (item) => {
  checked.value = item.id;
  isUpdateList.value = false;
  obj.lat = item.location.lat;
  obj.lng = item.location.lng;

  // 更新地图中心点
  map.setCenter(new TMap.LatLng(obj.lat, obj.lng));
  setTimeout(() => {
    isUpdateList.value = true;
  }, 100);
};

const searchHandle = () => {
  if (!keyword.value) {
    return;
  }
  checked.value = null;
  loading.value = true;
  axios
    .get("https://app.diaochan88.com/api/index/searchAddress", {
      params: {
        words: keyword.value,
        location: `${obj.lat},${obj.lng}`,
      },
    })
    .then((res) => {
      if (res.data.data.data.length === 0) {
        queryRegion();
      } else {
        loading.value = false;
        address.value.pois = res.data.data.data;
      }
    });
};

/**
 * 查询行政区
 */
const queryRegion = () => {
  axios
    .get("https://app.diaochan88.com/api/index/searchAddress", {
      params: {
        words: keyword.value,
        location: `${obj.lat},${obj.lng}`,
        boundary: `region(${keyword.value},1,${obj.lat},${obj.lng})`,
      },
    })
    .then((res) => {
      const [region] = res.data.data.data;
      obj.lat = region.location.lat;
      obj.lng = region.location.lng;

      searchHandle();
    });
};

const confirmSelection = () => {
  // 将选中的位置传递给uni-app
  window.uni.postMessage({
    data: {
      type: "mapSelection",
      location: obj,
    },
  });
};

// UP5BZ-4CYLM-NQM6W-665FE-UWNC7-PWF6J
let map = null;
const markerGeo = ref(null);
let markerLayer = null;

function initMap() {
  //定义地图中心点坐标
  var center = new TMap.LatLng(29.559955142971372, 106.58220481624915);
  //定义map变量，调用 TMap.Map() 构造函数创建地图

  map = new TMap.Map(document.getElementById("map"), {
    center: center, //设置地图中心点坐标
    zoom: 17.2, //设置地图缩放级别
    // pitch: 43.5, //设置俯仰角
    rotation: 45, //设置地图旋转角度
  });

  markerGeo.value = {
    id: "center",
    position: map.getCenter(),
  };

  // 创建一个位于地图中心点的marker
  markerLayer = new TMap.MultiMarker({
    map: map,
    geometries: [markerGeo.value],
    // styles: {
    //   marker: new TMap.MarkerStyle({
    //     width: 25,
    //     height: 35,
    //     anchor: { x: 16, y: 32 },
    //     src: "https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/markerDefault.png",
    //   }),
    // },
  });

  // 监听中心点变化事件，更新marker的位置
  map.on("center_changed", () => {
    markerGeo.value.position = map.getCenter();
    markerLayer.updateGeometries([markerGeo.value]);
  });

  //监听地图平移结束
  map.on("panend", function () {
    // 获取平移后的坐标
    const center = map.getCenter();
    // 更新obj的值
    if (center && isUpdateList.value) {
      obj.lat = center.lat;
      obj.lng = center.lng;
      // 可以在这里调用搜索接口，获取新的地址列表

      debouncedGetLocation();
    }
  });

  // 移除控件
  map.removeControl(TMap.constants.DEFAULT_CONTROL_ID.ZOOM);
  map.removeControl(TMap.constants.DEFAULT_CONTROL_ID.ROTATION);
  map.removeControl(TMap.constants.DEFAULT_CONTROL_ID.SCALE);
  map.removeControl(TMap.constants.DEFAULT_CONTROL_ID.FLOOR);
}

const debouncedGetLocation = debounce(function () {
  getLocation();
}, 1000);

const getLocation = () => {
  if (!isUpdateList.value) {
    return;
  }
  loading.value = true;
  axios
    .get("https://app.diaochan88.com/api/index/getMapAddress", {
      params: {
        location: `${obj.lat},${obj.lng}`,
      },
    })
    .then((res) => {
      address.value = res.data.data.result;
    })
    .finally(() => {
      loading.value = false;
    });
};

onMounted(() => {
  initMap();
  getLocation();
});

const back = () => {
  uni.navigateBack({
    delta: 1,
  });
};
</script>

<style lang="scss" scoped>
.page {
  position: relative;
  width: 100%;
  height: 100%;
  #map {
    width: 100vw;
    height: 60vh;
  }
  .back {
    position: absolute;
    top: 10px;
    left: 10px;
    z-index: 9999;
    width: 40px;
    height: 40px;
    display: flex;
    justify-content: center;
    align-items: center;
    background: rgba(255, 255, 255, 0.4);
    border-radius: 50%;
    box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.1);
    cursor: pointer;
  }
  .container {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 1000;
    width: 100%;
    height: 50vh;
    background: rgba(255, 255, 255, 0.8);
    .bg {
      width: calc(100% - 24px);
      box-sizing: border-box;
      margin: 12px;
      background: #fff;
      .search {
        padding: 5px 15px;
        height: 50px;
        display: flex;
        align-items: center;
        box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.1);
        border-radius: 8px;
        .input {
          height: 40px;
          flex: 1;
          outline: none;
          border: none;
          padding-left: 15px;
          &::placeholder {
            color: #999;
          }
        }
        .btn {
          color: #67c23a;
          font-size: 18px;
          font-weight: bold;
          position: relative;
        }
      }
      .address {
        margin-top: 10px;
        padding: 5px 15px;
        box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.1);
        border-radius: 8px;

        height: calc(50vh - 50px - 90px);
        overflow-y: scroll;

        padding-bottom: 40px;

        .item {
          display: flex;
          align-items: center;
          padding: 10px 0;
          border-bottom: 1px solid #f0f0f0;
          .info {
            padding-left: 10px;
            flex: 1;
            .title {
              font-size: 15px;
            }
            .address-info {
              margin-top: 5px;
              color: #999;
              font-size: 12px;
              .distance {
                padding-right: 10px;
              }
            }
          }
          .check {
            padding-left: 10px;
            width: 20px;
            height: 20px;
          }
        }
      }
      .confirm {
        position: absolute;
        bottom: 10px;
        left: 50%;
        transform: translateX(-50%);
        width: 50%;
        height: 40px;
        line-height: 40px;
        text-align: center;
        background: #67c23a;
        color: #fff;
        border-radius: 8px;
        font-size: 16px;
        font-weight: bold;
        box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.1);
        cursor: pointer;
      }
    }
  }
  .loading {
    display: flex;
    justify-content: center;
    align-items: center;
    .loading-box {
      width: 50px;
      height: 50px;
      animation: loading 1s linear infinite;
    }
    .img {
      width: 50px;
      height: 50px;
    }
  }
  .img {
    width: 30px;
    height: 30px;
  }
  .item-img {
    width: 20px;
    height: 20px;
  }
}

@keyframes loading {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>
